package com.example.demo.http.controllers.admin;

import cn.hutool.core.date.DateUtil;
import com.example.demo.models.Activity;
import com.example.demo.models.admin.ActivityAdmin;
import com.example.demo.models.admin.ActivityAdminLog;
import com.example.demo.models.admin.Admin;
import com.example.demo.models.user.User;
import com.example.demo.services.system.ResultService;
import com.example.demo.services.system.UserService;
import gaarason.database.appointment.OrderBy;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/admin/activity/admin/")
public class ActivityAdminController {
    @Resource
    Activity.Model activityModel;
    @Resource
    ActivityAdminLog.Model activityAdminLogModel;
    @Resource
    ActivityAdmin.Model activityAdminModel;
    @Resource
    User.Model userModel;

    //查询需要你审核的活动
    @GetMapping("/")
    ResultService.Result index(@RequestParam Map<String, String> params) {
        //当前管理员
        Admin user = UserService.getThreadInstance().getAdmin();
        //首先查出要当前管理员审核的所有活动
        RecordList<ActivityAdminLog, Long> activityAdminLogList = activityAdminLogModel.newQuery().where(ActivityAdminLog::getResult, user.getNumber()).where(ActivityAdminLog::getStatus, "1").get();
        //然后获取他们所有的id，并且从活动中查出来所有id
        List<String> activityIdList = new ArrayList<>();
        for (Record<ActivityAdminLog, Long> activityAdminLog : activityAdminLogList) {
            //获得活动id
            activityIdList.add(activityAdminLog.getEntity().getActivity_id());
        }
        // Todo 等待后面再重写，传入当前记录id和活动id，通过活动id查询进行结合组合，还没来得及做
        //分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            //如果没有页数，默认为第一页
            page = "1";
        }
        //按照分页进行数据获取
        Builder<Activity, Long> builder = activityModel.newQuery().whereIn(Activity::getId, activityIdList).select(Activity::getId, Activity::getTitle, Activity::getNumber, Activity::getCreatedAt).orderBy(Activity::getId, OrderBy.DESC);
        //放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                //要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });
        //生成数据列表
        List<Map<String, String>> data = new ArrayList<>();
        //返回结果
        Paginate<Activity> paginate = builder.paginate(page, 15);
        //对结果进行处理
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("currentPage", paginate.getCurrentPage());
        resultData.put("lastPage", paginate.getLastPage());
        resultData.put("total", paginate.getTotal());
        resultData.put("perPage", paginate.getPerPage());

        for (Activity activity : paginate.getItemList()) {
            Map<String, String> temp = new LinkedHashMap<>();
            temp.put("id", String.valueOf(activity.getId()));
            temp.put("title", activity.getTitle());
            temp.put("number", activity.getNumber());
            temp.put("created_at", DateUtil.format(activity.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"));
            //循环填充数据
            for (Record<ActivityAdminLog, Long> activityAdminLog : activityAdminLogList) {
                if (activityAdminLog.getEntity().getActivity_id().equals(String.valueOf(activity.getId()))) {
                    temp.put("activity_admin_id", String.valueOf(activityAdminLog.getEntity().getId()));
                    break;
                }
            }
            data.add(temp);
        }
        resultData.put("data", data);
//        //生成查询器
//        Builder<Activity, Long> builder = activityModel.newQuery().whereIn("id", activityIdList);

//
//        //返回结果
//        Paginate<Activity> paginate = builder.paginate(page, 15);
//        //对结果进行处理
//        Map<String, Object> data = new HashMap<>();
//        data.put("currentPage", paginate.getCurrentPage ());
//        data.put("lastPage", paginate.getLastPage());
//        data.put("total", paginate.getTotal());
//        data.put("perPage", paginate.getPerPage());
//        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = resultData;
        return result;
    }

    //获得可用的可以被发布给的管理员的名单
    @GetMapping("/getAdmin")
    ResultService.Result getAdmin(@RequestParam Map<String, String> params) {
        ResultService.Result result = ResultService.getNormalResult();
        if (Objects.isNull(params.get("rank"))) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "你需要提交等级";
            return result;
        }
        //当前管理员
        Admin admin = UserService.getThreadInstance().getAdmin();
        //根据管理员信息获得学院
        String college = admin.getCollege();
        //获得学号后，根据活动管理员表，查出可以被提交的等级人员
        RecordList<ActivityAdmin, Long> record = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, college).where(ActivityAdmin::getRank, params.get("rank")).orderBy(ActivityAdmin::getId, OrderBy.ASC).select(ActivityAdmin::getNumber).get();
        //根据这个人员组出一个“学号，姓名”列表
        List<Map<String, String>> list = new ArrayList<>();
        for (Record<ActivityAdmin, Long> activityAdmin : record) {
            String number = activityAdmin.getEntity().getNumber();
            Long id = activityAdmin.getEntity().getId();
            //根据学号查出这个人具体是谁
            Record<User, Long> tempUser = userModel.newQuery().where(User::getNumber, number).first();
            Map<String, String> temp = new LinkedHashMap<>();
            temp.put("id", String.valueOf(id));
            temp.put("number", number);
            if (tempUser != null) {
                temp.put("name", tempUser.getEntity().getName());
            } else {
                temp.put("name", "");
            }
            list.add(temp);
        }
        result.data = list;
        return result;
    }

    //提交活动审核
    @PostMapping("/submit")
    ResultService.Result submit(@RequestParam Map<String, String> params) {
        ResultService.Result result = ResultService.getNormalResult();
        //当前管理员
        Admin admin = UserService.getThreadInstance().getAdmin();
        //判断一下有没有提交通过和不通过
        if (Objects.isNull(params.get("submit"))) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "活动审核未提交";
            return result;
        }
        //判断有没有审核记录id
        if (Objects.isNull(params.get("id"))) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "活动审核记录不存在";
            return result;
        }
//        if (Objects.isNull(params.get("admin_id"))) {
//            //如果没找到管理员id，说明没有提交，直接报错
//            result.code = ResultService.CLIENT_ERROR;
//            result.msg = "请选择下一级管理员";
//            return result;
//        }
//        //首先查一下下一级管理员在不在
//        Record<ActivityAdmin, Long> activityAdmin = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, admin.getCollege()).find(params.get("admin_id"));
//        //如果下一级管理员不在，直接打回
//        if (activityAdmin == null) {
//            result.code = ResultService.CLIENT_ERROR;
//            result.msg = "请选择下一级管理员";
//            return result;
//        }
        //获得这条记录
        Record<ActivityAdminLog, Long> activityAdminLog = activityAdminLogModel.newQuery().where(ActivityAdminLog::getResult, admin.getNumber()).find(params.get("id"));
        if (Objects.isNull(activityAdminLog)) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "活动审核记录不存在";
            return result;
        }
        //判断这条记录状态是否已经变更
        if (!activityAdminLog.getEntity().getStatus().equals("1")) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "活动审核记录状态不正确";
            return result;
        }
        //上一个审核等级
        Long beforeRank = Long.parseLong(activityAdminLog.getEntity().getRank());
        //当前审核等级
        Long thisRank = beforeRank + 1;
        //判断当前这个是不是终审，方法是用学号、学院、rank全部放进去搜
        Record<ActivityAdmin, Long> activityAdmin = activityAdminModel.newQuery().where(ActivityAdmin::getNumber, admin.getNumber()).where(ActivityAdmin::getCollege, admin.getCollege()).where(ActivityAdmin::getRank, thisRank).first();
        if (Objects.isNull(activityAdmin)) {
            //如果是空的，说明没有审核能力，直接报错
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "审核权限状态不正确";
            return result;
        }
        String submit = params.get("submit");
        //新的一个活动审核记录
        Record<ActivityAdminLog, Long> newActivityAdminLog = activityAdminLogModel.newRecord();
        newActivityAdminLog.getEntity().setActivity_id(String.valueOf(activityAdminLog.getEntity().getActivity_id()));
        newActivityAdminLog.getEntity().setNumber(admin.getNumber());
        //默认当前是最新审核记录
        newActivityAdminLog.getEntity().setRank(String.valueOf(thisRank));
        if (activityAdmin.getEntity().getIsEnd().equals("1")) {
            //如果isEnd是1，则说明这个是终审
            newActivityAdminLog.getEntity().setStatus("0");
            if ("true".equals(submit)) {
                //只要submit是true，则代表审核通过
                newActivityAdminLog.getEntity().setData("审核通过");
                //审核通过后，通过调整活动的is_open去允许活动给用户进行操作
                Record<Activity, Long> activityRecord = activityModel.newQuery().find(activityAdminLog.getEntity().getActivity_id());
                //活动开放
                activityRecord.getEntity().setIsOpen(1);
                activityRecord.save();
            } else {
                newActivityAdminLog.getEntity().setData("审核不通过");
            }
        } else {
            if ("true".equals(submit)) {
                //如果isEnd不是1，则说明还有下一个
                newActivityAdminLog.getEntity().setStatus("1");
                //判断有没有下一级管理员
                if (Objects.isNull(params.get("admin_id"))) {
                    //如果没找到管理员id，说明没有提交，直接报错
                    result.code = ResultService.CLIENT_ERROR;
                    result.msg = "请选择下一个管理员";
                    return result;
                }
                //判断下一个等级管理员是否存在
                Long nextRank = thisRank + 1;
                //首先查一下下一级管理员在不在
                Record<ActivityAdmin, Long> nextActivityAdmin = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, admin.getCollege()).where(ActivityAdmin::getRank, nextRank).find(params.get("admin_id"));
                //如果下一级管理员不在
                if (nextActivityAdmin == null) {
                    //判断一下是不是这一级管理员，是的话调整调整rank
                    nextActivityAdmin = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, admin.getCollege()).where(ActivityAdmin::getRank, thisRank).find(params.get("admin_id"));
                    if (nextActivityAdmin == null) {
                        result.code = ResultService.CLIENT_ERROR;
                        result.msg = "请选择下一个管理员";
                        return result;
                    } else {
                        //因为是同级管理员，因此跳为上一次审核等级
                        newActivityAdminLog.getEntity().setRank(String.valueOf(beforeRank));
                    }
                } else {
                    //配置下一级审核等级
                    newActivityAdminLog.getEntity().setRank(String.valueOf(thisRank));
                }
                //找到下一个管理员，进行审核提交
                newActivityAdminLog.getEntity().setData("当前审核通过");
                newActivityAdminLog.getEntity().setResult(activityAdmin.getEntity().getNumber());
            } else {
                newActivityAdminLog.getEntity().setData("当前审核不通过");
            }
        }
        //保存结果
        newActivityAdminLog.save();
        return result;
    }

    @GetMapping("/record")
        ResultService.Result indexRecord(@RequestParam Map<String, String> params) {
        //分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            //如果没有页数，默认为第一页
            page = "1";
        }
        //生成查询器
        //查询限制只查询开放的活动
        Builder<ActivityAdminLog, Long> builder = activityAdminLogModel.newQuery();
        //放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                //要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });
        //返回结果
        Paginate<ActivityAdminLog> paginate = builder.paginate(page, 15);
        //对结果进行处理
        Map<String, Object> data = new HashMap<>();
        data.put("currentPage", paginate.getCurrentPage());
        data.put("lastPage", paginate.getLastPage());
        data.put("total", paginate.getTotal());
        data.put("perPage", paginate.getPerPage());
        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = data;
        return result;
    }
}
